package routers

import (
	"net/http"

	"gitee.com/kessil/chicory/internal/config"
	"gitee.com/kessil/chicory/internal/middleware"
	"gitee.com/kessil/chicory/internal/models"
	"gitee.com/kessil/chicory/internal/repositories"

	"github.com/go-chi/chi/v5"
	"xorm.io/xorm"
)

type PermissionRouter struct {
	*GenericCRUDRouter[models.Permission]
	db   *xorm.Engine
	cfg  *config.Config
	repo *repositories.PermissionRepository
}

func NewPermissionRouter(db *xorm.Engine, cfg *config.Config) *PermissionRouter {
	// 定义允许筛选的字段
	allowedFields := []string{"code", "name", "type", "parentId", "path",
		"redirect", "icon", "component", "layout",
		"keepAlive", "enable", "show", "method", "description"}

	// // 定义Patch忽略的字段
	// ignoreFields := []string{"id", "children", "created", "updated", "deleted"}

	genericRouter := NewGenericCRUDRouter[models.Permission](db, cfg, "permission", allowedFields)

	return &PermissionRouter{
		GenericCRUDRouter: genericRouter,
		db:                db,
		cfg:               cfg,
		repo:              repositories.NewPermissionRepository(db),
	}
}

func (pr *PermissionRouter) Routes() chi.Router {
	r := chi.NewRouter()

	r.Use(middleware.JWTAuthMiddleware(pr.cfg))

	// 继承泛型CRUD路由（已经包含分页和查询中间件）
	r.Mount("/", pr.GenericCRUDRouter.Routes())

	// 添加权限特有的路由
	r.Get("/tree", pr.tree)
	r.Get("/menu/tree", pr.menu)
	r.With(middleware.IDParamMiddleware("parentId")).Get("/button/{parentId}", pr.button)

	return r
}

func (pr *PermissionRouter) tree(w http.ResponseWriter, r *http.Request) {

	tree, err := pr.repo.GetAllPermissionTree()
	if err != nil {
		middleware.JSONError(w, http.StatusInternalServerError, "Failed to query permission tree")
		return
	}
	middleware.JSONSuccess(w, tree)
}

func (pr *PermissionRouter) menu(w http.ResponseWriter, r *http.Request) {
	perms, err := pr.repo.GetAllPermissionMenuTree()
	if err != nil {
		middleware.JSONError(w, http.StatusInternalServerError, "Faild to query permissions tree by roleIds")
		return
	}
	middleware.JSONSuccess(w, perms)
}

func (pr *PermissionRouter) button(w http.ResponseWriter, r *http.Request) {
	parentId := middleware.GetIDFromContext(r, "parentId")
	perms, err := pr.repo.GetButtonPermissionByParentId(parentId)
	if err != nil {
		middleware.JSONError(w, http.StatusInternalServerError, "Faild to query button permissions by parentId")
		return
	}
	middleware.JSONSuccess(w, perms)
}
